package net.ib.mtalk.network.task;

import java.util.UUID;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.UUIDSlicePredicate;
import net.ib.mntalk.protocol.Common.UUIDSliceRange;
import net.ib.mntalk.protocol.Common.ViewInfo;
import net.ib.mntalk.protocol.Session.GetMembersReq;
import net.ib.mntalk.protocol.Session.GetViewsReq;
import net.ib.mntalk.protocol.Session.GetViewsRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.helper.InboxDatabaseHelper;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.network.MethodId;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.ui.chat.ChatListActivity;
import net.ib.mtalk.ui.inbox.InboxListActivity;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.os.Handler;

public class GetViewsTask extends AsyncNetTask {

	private GetViewsReq mGetViesReq;
	
	public GetViewsTask(Context context, Handler handler, GetViewsReq getViewsReq){
		super(context, handler);
		this.mGetViesReq = getViewsReq;
	}
	
	@Override
	protected TcpEnvelope onPreExecute() {
		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(mGetViesReq)
			.setMethodId(MethodId.Session.View.GetViews)
			.build();
		return rev;
	}
	
	@Override
	protected void onPostExecute(int resultCode, Object sentObject,
			Object receivedObject) {
		MTalkLogWriter.d("GetViewTask.onPostExecute() resultCode : " + resultCode);
		if(receivedObject == null){
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		GetViewsRes getViewsRes = (GetViewsRes) resultEnvelope.getMessage();
		
		MTalkLogWriter.d("GetViewTask ResponseCode : " + getViewsRes.getResponseCode());
		
		if(getViewsRes.getResponseCode() == Common.SUCCESS){
			// 디비 작업
//			InboxDatabaseHelper.insertSyncView(mContext, getViewsRes);
			ViewInfo viewInfo = new ViewInfo();
			for(int i = 0; i < getViewsRes.getViewCount(); i++){
				viewInfo = getViewsRes.getView(i);
				UUID clientViewUuid = InboxDatabaseHelper.syncView(mContext, viewInfo);
				switch(viewInfo.getType()){
					case Common.BROADCAST:
					case Common.GROUP_CHAT:
						UUIDSliceRange range = new UUIDSliceRange();
						range.setAscending(true);
						range.setMaxCount(ChatListActivity.GET_MEMBER_COUNT);
						
						GetMembersReq getMembersReq = new GetMembersReq();
						getMembersReq.setRange(range);
						getMembersReq.setViewUuid(viewInfo.getViewUuid());
						
						GetMembersTask task = new GetMembersTask(mContext, mUiHandler, 
								clientViewUuid.getMostSignificantBits(), clientViewUuid.getLeastSignificantBits(), 
								getMembersReq);
						task.execute();
						break;
					case Common.ONE_TO_ONE:
					default:
						break;
				}
				// NotiUUID를 설정해준다.
				if(getViewsRes.getView(i).hasLatestMessage()){
					GlobalPreferences.setLastViewChangedNotiUUID(getViewsRes.getView(i).getLatestMessage().getNotiUuid());
				}
			}
			// 노티 설정
			GlobalPreferences.setLastViewChangedNotiUUID(getViewsRes.getNotiUuid());
			
			// 뷰가 설정된 카운트 보다 많을때 다시 요청을 한다.
			if(getViewsRes.getViewCount() >= InboxListActivity.GET_VIEWS_COUNT){
				UUIDSliceRange slice_range = new UUIDSliceRange();
				slice_range.setStart(getViewsRes.getView(getViewsRes.getViewCount()-1).getViewUuid());
				slice_range.setAscending(true);
				slice_range.setMaxCount(InboxListActivity.GET_VIEWS_COUNT);
				UUIDSlicePredicate predicate = new UUIDSlicePredicate();
				predicate.setSliceRange(slice_range);
				GetViewsReq getViewsReq = new GetViewsReq();
				getViewsReq.setPredicate(predicate);
				try{
					MTalkLogWriter.d("InboxController.getViews()");
					GetViewsTask task = new GetViewsTask(mContext, mUiHandler, getViewsReq);
					task.execute();
				} catch(Exception e) {
					MTalkLogWriter.e(e);
				}
			}
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_GET_VIEWS_SUCCESS));
		} else{
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_GET_VIEWS_FAIL));
		}
	}
}
